/*
 * Copyright 2010-2012 Susanta Tewari. <freecode4susant@users.sourceforge.net>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

/*
* CheckTreeCellRenderer.java
*
* Created on December 29, 2007, 10:20 AM
*
* To change this template, choose Tools | Template Manager
* and open the template in the editor.
 */
package javautil.swing.tree;

import java.awt.BorderLayout;
import java.awt.Component;

import javax.swing.JPanel;
import javax.swing.JTree;
import javax.swing.tree.TreeCellRenderer;
import javax.swing.tree.TreePath;

/**
 *
 * @author stewari1
 */
class CheckTreeCellRenderer extends JPanel implements TreeCellRenderer {

    /** Field description */
    private final TristateCheckBox checkBox = new TristateCheckBox();

    /** Field description */
    private final CheckTreeSelectionModel selectionModel;

    /** Field description */
    private final TreeCellRenderer delegate;

    /**
     * Constructs ...
     *
     * @param delegate description
     * @param selectionModel description
     */
    public CheckTreeCellRenderer(TreeCellRenderer delegate,
                                 CheckTreeSelectionModel selectionModel) {

        this.delegate       = delegate;
        this.selectionModel = selectionModel;

        setLayout(new BorderLayout());
        setOpaque(false);
        checkBox.setOpaque(false);
    }

    public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected,
            boolean expanded, boolean leaf, int row, boolean hasFocus) {

        Component renderer = delegate.getTreeCellRendererComponent(tree, value, selected, expanded,
                                 leaf, row, hasFocus);
        TreePath path = tree.getPathForRow(row);

        if (path != null) {

            if (selectionModel.isPathSelected(path, true)) checkBox.setState(Boolean.TRUE);
            else checkBox.setState(selectionModel.isPartiallySelected(path) ? null : Boolean.FALSE);
        }

        removeAll();
        add(checkBox, BorderLayout.WEST);
        add(renderer, BorderLayout.CENTER);

        return this;
    }
}
